package com.app.net;

import java.io.File;
import java.util.ArrayList;

import org.apache.http.message.BasicNameValuePair;
import org.json.JSONException;

import android.app.DownloadManager;
import android.app.DownloadManager.Request;
import android.content.Context;
import android.database.ContentObserver;
import android.database.Cursor;
import android.net.Uri;
import android.os.Environment;
import android.os.Handler;

import com.app.util.Utils_Log;

/* @author sinawear
 * 540126629@qq.com
 */
public abstract class NetHelper_File {

	static final String TAG = "NetHelper_File";

	Handler handler = new Handler() {

		public void handleMessage(android.os.Message msg) {

			String str = (String) msg.obj;
			Utils_Log.e(TAG, str);

			try {

				onComplete(str);
			} catch (JSONException e) {

				e.printStackTrace();
				System.out.println("JSONException: " + e.toString());
			}

		};
	};

	// 需要的两个参数
	String url = "";
	ArrayList<BasicNameValuePair> map = new ArrayList<BasicNameValuePair>();
	Params params = new Params();

	DownloadsChangeObserver mDownloadObserver = new DownloadsChangeObserver();

	public abstract String init(ArrayList<BasicNameValuePair> map_url,
			Params params);

	public abstract void onComplete(String message) throws JSONException; // 并不会强制要函数体内,必须会有json异常跑出呢..

	// 提供参数
	public class Params {
		public String TipTitle = "";
		public String TipDescription = "";

	};

	Context mContext;
	DownloadManager mDM;
	long mDownloadId;

	// String mTipTitle="", mTipDescription="";
	public NetHelper_File(Context context) {
		this.mContext = context;
		mDM = (DownloadManager) context
				.getSystemService(Context.DOWNLOAD_SERVICE);

	}

	public void start() {

		url = init(map, params);
		if (url.length() == 0)
			return;

		/*
		 * mTipTitle = params.TipDescription; mTipDescription =
		 * params.TipDescription;
		 */

		/*
		 * String strNetRespone = download( ); Message msg = new Message();
		 * msg.obj = strNetRespone; handler.sendMessage(msg);
		 */
		download();

	}

	public void stop() {
		mDM.remove(mDownloadId);
	}

	private void download() {
		Request request = new Request(Uri.parse(url));

		 // 修改下载名称
		 int pos = url.lastIndexOf("/");
		 String FileName = url.substring(pos+1);

		 
//		 request.setAllowedNetworkTypes(Request.NETWORK_MOBILE | request.NETWORK_WIFI);
		request.setAllowedOverRoaming(true)
				// 缺省是true
				.setTitle(params.TipTitle)
				// 用于信息查看
				.setDescription(params.TipDescription)
				// 用于信息查看
				.setDestinationInExternalPublicDir(
						Environment.DIRECTORY_DOWNLOADS, FileName)
				.setVisibleInDownloadsUi(false);
		mDownloadId = mDM.enqueue(request); // 加入下载队列

		// 监听下载进度
		Cursor c = mDM.query(new DownloadManager.Query().setFilterById(mDownloadId));
		c.registerContentObserver(mDownloadObserver); 
		

	}

	// --
	private class DownloadsChangeObserver extends ContentObserver {

		public DownloadsChangeObserver() {
			super(new Handler());
		}

		@Override
		public void onChange(boolean selfChange) {
			// 查询需要监听的字段
			// 比如要监听实时下载进度，查看当前下载状态：是否已经断开，或者下载失败等等

			System.out.println("selfChange: " + selfChange);

			Cursor c = mDM.query(new DownloadManager.Query()
					.setFilterById(mDownloadId));
			int mSizeColunmId = c
					.getColumnIndexOrThrow(DownloadManager.COLUMN_BYTES_DOWNLOADED_SO_FAR);

			if (c.moveToFirst()) {

				int bytesWritten = c.getInt(mSizeColunmId);
				int totalSize = c
						.getInt(c
								.getColumnIndex(DownloadManager.COLUMN_TOTAL_SIZE_BYTES));

				// if(bytesWritten != totalSize )
				{
					onProgress(bytesWritten, totalSize);
				}
				/*
				 * else if(bytesWritten == totalSize){ // 完成后会进入3次 int
				 * statusCode =200; File file = new File(
				 * getDownloadFileName(mDownloadId) );
				 * 
				 * onSuccess(statusCode, file);
				 * 
				 * 
				 * }
				 */

				if (bytesWritten == totalSize) { // 下载成功

					final int statusCode = 200;
					final File file = new File(getDownloadFileName(mDownloadId));

					handler.postDelayed(new Runnable() {

						@Override
						public void run() {

							onSuccess(statusCode, file);
						}
					}, 800);

					// c.unregisterContentObserver(mDownloadObserver);

				}

			}// endif

			c.close();

		}

	}

	private String getDownloadFileName(long download_id) {
		Uri videoUrl = mDM.getUriForDownloadedFile(download_id);

		DownloadManager.Query query = new DownloadManager.Query();
		Cursor cursor = mDM.query(query.setFilterById(download_id));
		int index = cursor
				.getColumnIndex(DownloadManager.COLUMN_LOCAL_FILENAME);

		int status = cursor.getColumnIndex(DownloadManager.COLUMN_STATUS);

		// if(g.DEBUG)
		{
			// String[] column_names = cursor.getColumnNames();
			// System.out.println(column_names);
		}

		cursor.moveToFirst();
		int row_count = cursor.getCount();
		String file_name = cursor.getString(index);

		return file_name;

	}

	public void onProgress(int bytesWritten, int totalSize) {
	}

	public void onSuccess(int statusCode, File file) {
	}

	public void onFailure(int statusCode, String content, Throwable error) {
	}

	/*
	 * // 监听下载结束，启用BroadcastReceiver public BroadcastReceiver receiver = new
	 * BroadcastReceiver() {
	 * 
	 * @Override public void onReceive(Context context, Intent intent) {
	 * 
	 * DownloadManager dm =
	 * (DownloadManager)context.getSystemService(Context.DOWNLOAD_SERVICE);
	 * String action = intent.getAction(); if
	 * (DownloadManager.ACTION_DOWNLOAD_COMPLETE.equals(action)) {
	 * 
	 * long downloadId = intent.getLongExtra( DownloadManager.EXTRA_DOWNLOAD_ID,
	 * 0); // 查询 Query query = new Query(); query.setFilterById(downloadId);
	 * Cursor c = dm.query(query); if (c.moveToFirst()) { int columnIndex = c
	 * .getColumnIndex(DownloadManager.COLUMN_STATUS); if
	 * (DownloadManager.STATUS_SUCCESSFUL == c .getInt(columnIndex)) {
	 * 
	 * String uriString = c .getString(c
	 * .getColumnIndex(DownloadManager.COLUMN_LOCAL_URI));
	 * 
	 * //removeDownload(downloadId); //
	 * Toast.makeText(CopyOf_43MainActivity.this, // "get file complete: " +
	 * uriString, 0).show(); // Uri.parse(uriString); int statusCode =200; File
	 * file = new File( getDownloadFileName(downloadId) ); onSuccess(statusCode,
	 * file);
	 * 
	 * } }// endif
	 * 
	 * }// endif
	 * 
	 * }// onReceive };// end class receiver
	 */

}
